// axios 二次封装

import axios from 'axios'
import Qs from 'qs'

axios.defaults.withCredentials = true;//true 跨域  false 不跨域
axios.defaults.headers.common["token"] = localStorage.getItem("token")//把token携带到请求头

// 引入vant的提示插件
import { Toast } from 'vant'

export default function (path, params, method = "get", headerType = "form") {
  let baseURL = "/api" //基本请求路径  代理后的服务器地址
  let data = {}
  if (method == "post") { //处理post请求设置不同请求头
    if (headerType == "json") {
      axios.defaults.headers.post["Content-Type"] =
        "application/json;charset=UTF-8";
      data = params;
    } else if (headerType == "multipart") {
      axios.defaults.headers.post["Content-Type"] = "multipart/form-data";
    } else {
      axios.defaults.headers.post["Content-Type"] =
        "application/x-www-form-urlencoded";
      data = Qs.stringify(params);  //表单类型数据 需要qs下
    }
  }
  // get 请求  参数携带到地址栏
  if (method == "get") {
    if (headerType != "json") {
      axios.defaults.headers["Content-Type"] =
        "application/x-www-form-urlencoded;charset=UTF-8";
    }
    data = Qs.stringify(params)//name=1&age=2
    path = path + "?" + data  //把传送的数据  拼接到地址栏
    data = {}
  }
  // 请求拦截器
  axios.interceptors.request.use(config => {
    // token拦截
    // let token = localStorage.token;
    // if (token) {
    //   config.headers["token"] = token;
    // }
    return config
  })

  //响应拦截器
  axios.interceptors.response.use(response => {
    if (response.data.code == 0) {
      Toast.fail("暂无数据")
    }
    if (response.data.code == 500001) {
      Toast.fail("登录过期从新登录")
    }
    return response
  })
  return new Promise((resolve, reject) => {
    axios({
      baseURL: baseURL,
      method,
      url: path,
      data: data,
      timeout: 6000
    }).then(res => {
      // resolve(res.data.result)//
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })

}
